import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:get/get.dart';
// import 'package:camera/camera.dart';
import 'package:path_provider/path_provider.dart';

import 'dart:async';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:rtmp_publisher/camera.dart';

import '../../main.dart';
import 'package:exams_app/home_module/exams_module/exams_page.dart';
import 'package:exams_app/home_module/exams_module/logic.dart';

class AiFacePage extends StatefulWidget {
  const AiFacePage({Key key}) : super(key: key);

  @override
  _AiFacePageState createState() => _AiFacePageState();
}

class _AiFacePageState extends State<AiFacePage> with WidgetsBindingObserver,TickerProviderStateMixin {

  HomeModuleLogic logic = Get.put(HomeModuleLogic());

  var imageFile0;

  var seconds = 2;

  Timer countdownTimer;

  CameraController controller;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    controller =
        CameraController(cameras[1], ResolutionPreset.medium, enableAudio: false);

    controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });




    // getcamer();

    countdownTimer =
    new Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (seconds > 0) {
          seconds--;
        } else {
          cancelTimer();
          print('倒计时结束');
          savaPic();
        }
      });
    });

  }

  randDomColor(){

    Color color;
    color = Color.fromRGBO(Random().nextInt(256), Random().nextInt(256),
        Random().nextInt(256), 1);

    return color;
  }

  void cancelTimer() {
    if (countdownTimer != null) {
      countdownTimer.cancel();
      countdownTimer = null;
    }
  }

  /// 自动识别
  void savaPic()async{
    String timestamp() =>
        DateTime.now().millisecondsSinceEpoch.toString();
    if (!controller.value.isInitialized) {
      print('Error: select a camera first.');
      return null;
    }
    // getApplicationDocumentsDirectory  文档目录
    final Directory extDir =
    await getApplicationDocumentsDirectory();
    final String dirPath =
        '${extDir.path}/Pictures/flutter_test';
    print(dirPath);
    await Directory(dirPath).create(recursive: true);
    final String filePath = '$dirPath/${timestamp()}.jpg';
    print(filePath);
    // imageFile0 = filePath;
    // if (controller.value.isTakingPicture) {
    //   // A capture is already pending, do nothing.
    //   print('E1111');
    //   return null;
    // }

    try {

      imageFile0 = filePath;
      await controller.takePicture(filePath);

      // XFile file = await controller.takePicture();
      // imageFile0 = file.path;
      print('保存成功');
      var imageys = await imageCompressAndGetFile(File(imageFile0));

      List bytes = await imageys.readAsBytes();

      String bs64 = base64Encode(bytes);

      String bs64Image = 'data:image/jpg;base64,${bs64}';

      logic.requestDataWithAIface(bs64Image).then((value) {

        if(value['errcode']==-100){
          BotToast.showText(text: value['message']);
          seconds = 2;
          countdownTimer =
          new Timer.periodic(new Duration(seconds: 1), (timer) {
            setState(() {
              if (seconds > 0) {
                seconds--;
              } else {
                countdownTimer.cancel();
                countdownTimer = null;
                print('倒计时结束');
                savaPic();
              }
            });
          });
        }else if(value['data']=='False'){
          BotToast.showText(text: '不是本人,请本人考试');
          seconds = 2;
          countdownTimer =
          new Timer.periodic(new Duration(seconds: 1), (timer) {
            setState(() {
              if (seconds > 0) {
                seconds--;
              } else {
                countdownTimer.cancel();
                countdownTimer = null;
                print('倒计时结束');
                savaPic();
              }
            });
          });
        }else if(value['data']=='True'){
          print('识别成功,跳转考试页面');

          Get.to(ExamsPage());
        } else{

          print('未知');
          // print('识别成功,跳转考试页面');
          //
          // Get.to(ExamsPage());
        }

      });

      setState(() {

      });
      // Get.to(DisplayPictureScreen(
      //   imagePath: file.path,
      // ));
    } on CameraException catch (e) {
      print('保存失败');
      print(e);
      return null;
    }
  }

  void dispose() {

    WidgetsFlutterBinding.ensureInitialized().removeObserver(this);

    cancelTimer();

    controller.dispose();

    super.dispose();
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(
          color: Colors.black, //修改颜色
        ),
        elevation: 0,
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text('人脸识别',style: TextStyle(color: Colors.black),),
      ),
      body: Stack(
        children: [
          Container(
            padding: EdgeInsets.only(top: 20),
            alignment: Alignment.center,
            width: Get.width,
            height: Get.height,
            color: randDomColor(),
            child: Column(
              children: [

                Text('人脸检测识别中',style: TextStyle(fontSize: 16,fontWeight: FontWeight.w500),),
                // Text('${seconds} s'),
              ],
            )
          ),
          Container(
            // color: Colors.red,
            margin: EdgeInsets.all(5),
            clipBehavior: Clip.antiAliasWithSaveLayer,
            // color: Colors.red,
            //边框设置
            decoration: new BoxDecoration(

              shape: BoxShape.circle,
            ),
            child: !controller.value.isInitialized?Container(
              child: Center(
                child: Text('没有找到可用的相机'),
              ),
            ):CameraPreview(
              controller,
            ),
          ),
        ],
      ),
    );
  }
}


